//小程序配置项
const appid = "你自己的appid";
const secret = "你自己小程序的秘钥";
const db = uniCloud.database();
//请求微信token令牌
async function accessToken(){
	let {data:{access_token}} = await uniCloud.request({
		url:"https://api.weixin.qq.com/cgi-bin/token",
		data:{
			grant_type:"client_credential",
			appid,
			secret
		}
	})
	return access_token
}
//判断数据库中是否存在token，存在并且没有超时间读数据库，反而发送网络请求获取token
async function dbAccessToken(){
	let {data:[dbToken]=[]} = await db.collection("WXaccessToken").orderBy("_id","desc").limit(1).get();		
	if(!dbToken){	
		console.log("创建token表");
		let acToken = await accessToken();
		await db.collection("WXaccessToken").add({tokenExpired:Date.now()+1000*60*60*2,accessToken:acToken})
		return acToken;
	}else if(dbToken.tokenExpired - Date.now() < 1000*60){
		console.log("覆盖已有token");
		let acToken = await accessToken();
		await db.collection("WXaccessToken").update({tokenExpired:Date.now()+1000*60*60*2,accessToken:acToken})
		return acToken
	}else{
		console.log("读取已有token");
		return dbToken.accessToken
	}
}


module.exports = {
	appid,
	secret,
	accessToken,
	dbAccessToken
} 

